import axios, { AxiosRequestConfig } from 'axios';
import { ElMessage } from "element-plus";
import router from '@/router/index';

function request(config: AxiosRequestConfig) {
  const instance = axios.create({
    timeout: 60000,
  });
  instance.interceptors.request.use(config => config, error => {
    console.log(error);
    return Promise.reject(error);
  });
  instance.interceptors.response.use(response => response, error => {
    console.log(`\n=== ${error.response.config.url} ===\n`, error.response);
    if (error?.response?.data?.errorMsg) {
      // if (error.response.data.errorCode == "TERM.0001") {
      //   message.error(error.response.data.errorMsg);
      //   localStorage.clear()
      //   return router.push('/login')
      // } else {
      ElMessage.error(error.response.data.errorMsg);
      // }
    }
    return Promise.reject(error);
  });
  return instance(config);
}

const http = {
  get(url: string, params: any) {
    const config = {
      method: 'get',
      url,
    } as AxiosRequestConfig;
    if (params) config.params = params;
    return request(config);
  },
  post(url: string, params: any) {
    const config = {
      method: 'post',
      url,
    } as AxiosRequestConfig;
    if (params) config.data = params;
    return request(config);
  },
  put(url: string, params: any) {
    const config = {
      method: 'put',
      url,
    } as AxiosRequestConfig;
    if (params) config.params = params;
    return request(config);
  },
  delete(url: string, params: any) {
    const config = {
      method: 'delete',
      url,
    } as AxiosRequestConfig;
    if (params) config.params = params;
    return request(config);
  },
};

export default http;
